import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/cms/cmsdialogscreen.dart';
import 'package:opene/ui/cms/cmsmodel.dart';
import 'package:toast/toast.dart';

import 'cmstallysubmitscreen.dart';

class CMSTallyScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CMSTallyScreenPage();
  }
}

class CMSTallyScreenPage extends StatefulWidget {
  @override
  _CMSTallyScreenPageState createState() => _CMSTallyScreenPageState();
}

class _CMSTallyScreenPageState extends BaseState<CMSTallyScreenPage> {
  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0, position;
  List<CMSTally> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Tally:Container";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getTallyContainerNo();
      });
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 5, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: setListView(),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        CMSTally tally = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 2, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => CMSTallySubmitScreen(cmsTally:tally)),
                      );
                    },
                    child: Text(
                    Utils.getStringisEmpty(tally.containerNo),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                  ),),
                ),
                GestureDetector(
                  onTap: () {
                    type = 0;
                    getWarehousingDetailTallyInfo(tally);
                  },
                  child: Container(
                    margin: EdgeInsets.only(left: 5, right: 10),
                    child: Image.asset(
                      'assets/images/details.png',
                      width: 20,
                      height: 20,
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    type = 1;
                    getWarehousingDetailTallyInfo(tally);
                  },
                  child: Container(
                    padding: EdgeInsets.all(3),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: MyAppTheme.nearlyBlue, // 背景颜色
                      borderRadius: BorderRadius.all(Radius.circular(5)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Complete',
                      style: MyAppTheme.captionWhite,
                    ), // 子控件，如果需要的话
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    // if (Utils.isEmpty(strDate)) {
    //   Toast.show("Please select Drop Date", duration: Toast.lengthShort, gravity: Toast.bottom);
    //   return;
    // }
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  void getTallyContainerNo() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.fbaTransNotifyTallyPendingContainers);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => CMSTally.fromJson(userJson)).toList());
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void getWarehousingDetailTallyInfo(CMSTally tally) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    Map<String, dynamic> map = new HashMap();
    map["id"] = tally.id;
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.fbaTransNotifyTallyGetTallyedDetailList, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      CMSTallyedDetail cmsTallyedDetail = CMSTallyedDetail.fromJson(baseResponse.data);

      if (cmsTallyedDetail == null) {
        return;
      }

      if (type == 1) {
        List<CMSTallyDetail> tallyedLists = new List();
        List<CMSTallyDetail> tallyedList = cmsTallyedDetail.tallyedList;
        if (tallyedList != null && tallyedList.length > 0) {
          for (CMSTallyDetail cmsTallyDetail in tallyedList) {
            if (cmsTallyDetail.num == 0) {
              tallyedLists.add(cmsTallyDetail);
            }
          }
        }
        if (tallyedLists.length == 0) {
          tallyFinish("${tally.id}");
          return;
        } else {
          cmsTallyedDetail.tallyedList = tallyedLists;
        }
      }
      showDialog(
        context: context,
        builder: (context) => CMSTallyedDetailDialog(type:type,tally: tally, tallyDetails: cmsTallyedDetail),
      ).then((value) => {
            if (value != null && value) {tallyFinish("${tally.id}")}
          });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void tallyFinish(String notifyId) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.fbaTransNotifyTallyGetNotifyComplete+ "/" + notifyId, method: BaseMethod.put);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      getTallyContainerNo();
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}
